import React from 'react';
import {StyleSheet, View, Dimensions, PanResponder} from 'react-native';
import {Image} from 'react-native-animatable';


const {width, height} = Dimensions.get('window');

const animiType = 'fadeIn';

const px = pxWidth => {
  if (width === 1) {
    return StyleSheet.hairlineWidth;
  }
  return Math.floor(width / 750 * pxWidth);
};

const defaultPagination = (props) => {
  const {current, count, dotStyle, dotActiveStyle} = props;
  const flexDirection = 'row';
  const arr = [];
  for (let i = 0; i < count; i++) {
    arr.push(
      <View
        key={`dot-${i}`}
        style={[
          dotStyle,
          i === current && dotActiveStyle,
        ]}
      />,
    );
  }
  return (
    <View style={[styles.pagination]}>
      <View style={{flexDirection}}>{arr}</View>
    </View>
  );
};

const images = [
  require('./images/01.png'),
  require('./images/02.png'),
  require('./images/03.png'),
  require('./images/04.png'),
  require('./images/05.png'),
]

export default class Carousel extends React.Component {

  static defaultProps = {
    pagination: defaultPagination,
    images: images,
  };

  state = {
    images: this.props.images,
    currentIndex: 0
  }

  componentWillMount() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,// 在用户开始触摸的时候（手指刚刚接触屏幕的瞬间），是否愿意成为响应者？
      onStartShouldSetPanResponderCapture: () => true,//
      onMoveShouldSetPanResponder: () => true,//如果View不是响应者，那么在每一个触摸点开始移动（没有停下也没有离开屏幕）时再询问一次：是否愿意响应触摸交互呢
      onMoveShouldSetPanResponderCapture: () => true,
      onPanResponderGrant: this.boxTouchStart,// View现在要开始响应触摸事件了。这也是需要做高亮的时候，使用户知道他到底点到了哪里。
      onPanResponderRelease: this.boxTouchEnd,// 触摸操作结束时触发，比如"touchUp"（手指抬起离开屏幕）。
      onPanResponderTerminate: this.boxTouchEnd,//响应者权力已经交出
    });
  }

  componentDidMount() {

    this.timer = setInterval(() => {
      if (this.state.currentIndex === this.state.images.length - 1) {
        if (!this.isGuest) {
          this.setState({
            currentIndex: 0,
          },()=>{
            this.animat();
          })
        }
      } else {
        if (!this.isGuest) {
          this.setState({
            currentIndex: this.state.currentIndex + 1,
          },()=>{
            this.animat();
          })
        }
      }
    }, 3000)
  }

  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }

  animat=()=>{
    this.refs[animiType](1000);
  }


  touchStartX = 0;
  isGuest = false; //是否使用手势

  // console.log('boxTouchStart gestureState', {dx, dy, dymoveX, moveY, numberActiveTouches, stateID, vx, vy, x0, y0});
  boxTouchStart = (e, gestureState) => {
    this.isGuest = true;
    this.touchStartX = gestureState.dx;

  }

  boxTouchEnd = (e, gestureState) => {
    const dx = gestureState.dx;
    if (dx > 100) {
      if (this.state.currentIndex === 0) {
        this.setState({
          currentIndex: this.state.images.length - 1,
        }, () => {
          this.animat();
          this.isGuest = false;
        })
      } else {
        this.setState({
          currentIndex: this.state.currentIndex - 1,
        }, () => {
          this.animat();
          this.isGuest = false;
        })
      }
    } else if (dx < -100) {
      if (this.state.currentIndex === this.state.images.length - 1) {
        this.setState({
          currentIndex: 0,
        }, () => {
          this.animat();
          this.isGuest = false;
        })
      } else {
        this.setState({
          currentIndex: this.state.currentIndex + 1,
        }, () => {
          this.animat();
          this.isGuest = false;
        })
      }
    } else {
      alert(this.state.currentIndex + 1 + '');
      this.isGuest = false;
    }
  }

  render() {
    return (
      <View
        {...this._panResponder.panHandlers}
        style={styles.carouselImg}>
        <Image
          ref={(ref) => this.refs = ref}
          style={styles.carouselImg}
          source={this.state.images[this.state.currentIndex]}
          resizeMode="stretch"
        />
        {this.renderDots(this.state.currentIndex)}
      </View>
    )
  }

  renderDots = (index) => {
    const pagination = this.props.pagination;
    const dotStyle = styles.dotStyle;
    const dotActiveStyle = styles.activeDotStyle;
    const count = this.state.images.length || 1;
    return pagination ? pagination({
      current: index,
      count,
      dotStyle,
      dotActiveStyle,
    }) : null;
  }
}

const CarouselHeight = 440;

const styles = StyleSheet.create({
  carouselImg: {
    width: px(750),
    height: px(CarouselHeight),
  },
  dotStyle: {
    width: px(32),
    height: 2,
    borderRadius: 2,
    backgroundColor: 'rgba(255, 255, 255, 0.68)',
    marginLeft: 2,
    marginRight: 2,
  },
  activeDotStyle: {
    width: px(32),
    height: 2,
    backgroundColor: 'red',
    borderRadius: 2,
    marginLeft: 2,
    marginRight: 2,
  },
  pagination: {
    position: 'absolute',
    alignItems: 'center',
    alignSelf: 'center',
    bottom: 10,
  },
})

